package com.example.mychat.Controller;

import com.example.mychat.entity.Comment;
import com.example.mychat.mapper.CommentMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Tag(name = "发表评论")
@Controller
@RequestMapping("/comment")
public class CommentController {
    @Resource
    HttpServletRequest req;

    @Resource
    CommentMapper commentMapper;

    @Operation(description = "发表评论")
    @PostMapping("")
    @ResponseBody
    public String publishComment(@RequestParam String text, @RequestParam int type, @RequestParam Long id) {
        String username = String.valueOf(req.getSession().getAttribute("username"));
        if (username.equals("null")) {
            return "用户未登录";
        }
        //type==1表示评论主体消息，type==2表示回复评论
        if (type == 1) {
            commentMapper.insert(new Comment(username, text, id));
        } else {
            Comment comment = commentMapper.selectById(id);
            commentMapper.insert(new Comment(username, comment.getUsername(), text, comment.getMessageId()));
        }
        return "success";
    }
}
